<template>
  <div>
    <InsertTagDialog ref="insertTagDialog" @saveTag="saveTag"/>
    <InsertDetailDialog ref="insertDetailDialog" @saveDetail="saveDetail"/>
    <div>
      <div style="display: inline-block">
        <el-button icon="el-icon-back" size="small" type="text" @click="goBack">返回</el-button>
      </div>
      <div style="display: inline-block">|</div>
      <div style="display: inline-block;">
        <div style="padding-bottom: 15px;margin-left:10px">
          <span style=" font-family: 'Microsoft YaHei',serif;display: inline-block">详情</span>
        </div>
      </div>
    </div>
    <el-container>
      <el-aside style="overflow-x: auto;" width="300px">
        <el-main style="padding-top: 5px; width: 300px; overflow-x: auto;">
          <!-- data-changes-scroll-top:	数据变化滚动条是否滚动到顶部  -->
          <u-table ref='tagTable'
                   :data="allTagTree"
                   :border="false"
                   :data-changes-scroll-top="false"
                   :height="tableHeight"
                   :treeConfig="{
                     children: 'children',
                     iconClose: 'el-icon-arrow-right',
                     iconOpen: 'el-icon-arrow-down',
                     expandAll: false,
                     expandRowKeys: expandRowKeyArray}"
                   beautify-table highlight-current-row row-id="id"
                   row-key="id"
                   use-virtual
                   @toggle-tree-expand="toggleTreeExpand"
                   @cell-click="handleTagChange">
            <u-table-column :tree-node="true"
                            label="分类标签列表"
                            prop="name">
              <template slot-scope="scope">
                <div @mouseenter="handleMouseOver(scope.row)" @mouseleave="handleMouseOut(scope.row)">
                  <span>{{ scope.row.name }}</span>
                  <el-button v-if="scope.row.showButton" class="inline reorder-button" icon="el-icon-plus"
                             title="新增"
                             @click.stop="addSubTag(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton" class="inline reorder-button" icon="el-icon-edit"
                             title="修改"
                             @click.stop="editTag(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton" class="inline reorder-button" icon="el-icon-delete"
                             plain title="删除"
                             type="danger" @click.stop="deleteTag(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton && scope.row.sort !== 0" class="inline reorder-button"
                             icon="el-icon-top"
                             title="上移"
                             @click.stop="tagMoveUp(scope.row)"></el-button>
                  <el-button v-if="scope.row.showButton &&
                                    (scope.row.sort + 1) < (allTagList.filter(item => item.parentId === scope.row.parentId).length)"
                             class="inline reorder-button" icon="el-icon-bottom"
                             title="下移"
                             @click.stop="tagMoveDown(scope.row)"></el-button>
                </div>
              </template>
            </u-table-column>
          </u-table>
        </el-main>
      </el-aside>
      <el-main style="padding-left: 10px; overflow: hidden;">
        <el-row height="40px">
          <el-col :span='4' style="border: 1px solid transparent">
            <el-button v-if="selectedTag.level > 1" type="primary" @click="addDetail">新增要点</el-button>
          </el-col>
          <el-col :span='4' style="border: 1px solid transparent">
            <el-button v-if="selectedTag.level > 1" @click="batchDelete">批量删除</el-button>
          </el-col>
          <el-col :offset="6" :span="10">
            <div>
              <div style="width: 430px;">
                <el-input v-model="examOutlineDetail.name" input placeholder="请输入要点名称"
                          @keyup.enter.native="advanceConfirm">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  <el-button slot="append" :icon="appendIcon" v-on:click="switchAppend"></el-button>
                </el-input>
              </div>
              <div v-if="showAdvance" id="advance" style="padding: 10px;float: right">
                <div class="block" style="margin-top: 10px">
                  <div style="width: 100px;display: inline-block;text-align: right">要求</div>
                  <div style="display: inline-block">
                    <el-input v-model="examOutlineDetail.requireValue" size="small" style="width: 300px;"></el-input>
                  </div>
                </div>
                <div class="block" style="margin-top: 10px">
                  <div style="width: 100px;display: inline-block;text-align: right">科目</div>
                  <div style="display: inline-block">
                    <el-input v-model="examOutlineDetail.subjectValue" size="small" style="width: 300px;"></el-input>
                  </div>
                </div>
                <div class="block" style="margin-top: 10px">
                  <div style="width: 100px;display: inline-block;text-align: right">知识点数</div>
                  <div style="display: inline-block">
                    <el-input-number v-model="examOutlineDetail.knowledgeNumStartIndex"
                                     :max="examOutlineDetail.knowledgeNumEndIndex"
                                     :min="1"
                                     controls-position="right" size="small"
                                     style="width: 135px;"/>
                    <span>至</span>
                    <el-input-number v-model="examOutlineDetail.knowledgeNumEndIndex"
                                     :min="examOutlineDetail.knowledgeNumStartIndex"
                                     controls-position="right"
                                     size="small"
                                     style="width: 135px;"/>
                  </div>
                </div>
                <div class="block" style="margin-top: 10px">
                  <div style="width: 100px;display: inline-block;text-align: right">题数</div>
                  <div style="display: inline-block">
                    <el-input-number v-model="examOutlineDetail.exerciseNumStartIndex"
                                     :max="examOutlineDetail.exerciseNumEndIndex"
                                     :min="1"
                                     controls-position="right" size="small"
                                     style="width: 135px;"/>
                    <span>至</span>
                    <el-input-number v-model="examOutlineDetail.exerciseNumEndIndex"
                                     :min="examOutlineDetail.exerciseNumStartIndex"
                                     controls-position="right"
                                     size="small"
                                     style="width: 135px;"/>
                  </div>
                </div>
                <div class="block" style="margin-top: 10px">
                  <div style="width: 100px;display: inline-block;text-align: right">创建日期</div>
                  <div style="display: inline-block">
                    <el-date-picker v-model="examOutlineDetail.dateRange" :picker-options="pickerOptions" align="right"
                                    end-placeholder="截止日期"
                                    range-separator="至" size="small"
                                    start-placeholder="开始日期" style="width: 300px;" type="daterange"
                                    unlink-panels value-format="yyyy-MM-dd">
                    </el-date-picker>
                  </div>
                </div>
                <div style="margin-top: 60px; right: 10px;">
                  <el-row>
                    <el-col :offset="6" :span="6">
                      <div style="margin-left: 90px;height: 32px; width: 88px;">
                        <el-button size="small" v-on:click="showAdvance = false">取 消</el-button>
                      </div>
                    </el-col>
                    <el-col :offset="2" :span="2">
                      <div style="margin-left: 30px;height: 32px; width: 88px;">
                        <el-button size="small" v-on:click="reset">重置</el-button>
                      </div>
                    </el-col>
                    <el-col :offset="2" :span="2">
                      <div div style="margin-left: 30px;height: 32px; width: 88px;">
                        <el-button size="small" type="success" v-on:click="advanceConfirm">确 定</el-button>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row style="padding-top: 5px;">
          <el-table :data="tableData" :height="tableHeight" border stripe style="width: 100%;"
                    @selection-change="handleSelectionChange">
            <el-table-column
              v-model="multipleSelection"
              align="center"
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column label="要点名" min-width="160" prop="name" show-overflow-tooltip></el-table-column>
            <el-table-column label="要求" prop="requireValue" show-overflow-tooltip width="80"></el-table-column>
            <el-table-column label="科目" prop="subjectValue" width="80"></el-table-column>
            <el-table-column label="所属分类" prop="" width="80">
              <template slot-scope="scope">
                <span v-html="UTIL.arrayToStr(findParentNode(scope.row.examOutlineTagId), 'name', '->')"></span>
              </template>
            </el-table-column>
            <el-table-column label="知识点数" prop="knowledgeNum" width="80">
              <template slot-scope="scope">
                <el-link type="success" @click="skipToExamKnowledge(scope.row)"
                         v-html="scope.row.knowledgeNum"></el-link>
              </template>
            </el-table-column>
            <el-table-column label="题数" prop="exerciseNum" width="80">
              <template slot-scope="scope">
                <el-link type="success" @click="skipToExerciseGroupLibTable(scope.row)"
                         v-html="scope.row.exerciseNum"></el-link>
              </template>
            </el-table-column>
            <el-table-column label="来源" prop="source" width="80">
              <template slot-scope="scope">
                <span v-html="CONST.SOURCE[scope.row.source]"></span>
              </template>
            </el-table-column>
            <el-table-column label="创建人" prop="createdBy" width="100">
              <template slot-scope="scope">
                <span v-html="$store.state.userList.find(user => user.userName === scope.row.createdBy).name"></span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdTime"
                             width="180"></el-table-column>
            <el-table-column fixed="right" label="操作" min-width="160">
              <template slot-scope="scope">
                <!-- 2级分类及以下的要点才可以操作 -->
                <span><el-link :disabled="selectedTag.level === undefined || selectedTag.level === 1"
                               @click.prevent="editDetail(scope.row)">编辑</el-link></span>
                <span><el-link :disabled="selectedTag.level === undefined || selectedTag.level === 1" type="danger"
                               @click.prevent="deleteDetail(scope.row)">删除</el-link></span>
                <span><el-link
                  :disabled="scope.row.sort === 0 || selectedTag.level === undefined || selectedTag.level === 1"
                  @click.prevent="detailMoveUp(scope.row)">上移</el-link></span>
                <span><el-link
                  :disabled="scope.row.sort === tableData.length - 1 || selectedTag.level === undefined || selectedTag.level === 1"
                  @click.prevent="detailMoveDown(scope.row)">下移</el-link></span>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <div>
            <el-pagination
              :current-page.sync="examOutlineDetail.currentPage"
              :page-size.sync="examOutlineDetail.pageSize"
              :page-sizes="[5, 10, 15, 20, 50, 100]"
              :total="totalNum"
              background
              layout="total, sizes, prev, pager, next, jumper"
              style="text-align: right;"
              @current-change="selectDetailPage"
              @size-change="selectDetailPage"></el-pagination>
          </div>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>
<script>

import InsertTagDialog from './InsertTagDialog';
import InsertDetailDialog from './InsertDetailDialog';

export default {
  name: "Detail",
  components: {InsertTagDialog, InsertDetailDialog},
  data() {
    return {
      tableHeight: 0,
      tableData: [],
      totalNum: 0,
      multipleSelection: [],
      examOutlineDetail: {
        currentPage: 1, // 第几页
        pageSize: 10, // 每页显示的数据个数
      },
      allTagTree: [],
      allTagList: [],
      selectedTag: {},
      expandRowKeyArray: [],
      showAdvance: false,
      appendIcon: "el-icon-caret-bottom",
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      examOutlineId: '',
      bookId: ''
    }
  },
  methods: {
    toggleTreeExpand() {
      this.expandRowKeyArray = this.$refs.tagTable.getTreeExpandRecords().map(item => item.id)
    },
    handleTagChange(row) {
      this.selectedTag = row;
      this.examOutlineDetail.examOutlineTagId = row.id;
      this.examOutlineDetail.tagLevel = row.level;
      this.examOutlineDetail.currentPage = 1;
      this.selectDetailPage();
    },
    selectAllTagList() {
      this.axios.get('/pmph/action/examOutline/selectAllTagList', {
        params: {
          examOutlineId: this.examOutlineId
        }
      }).then((response) => {
        this.allTagList = response.data;
        this.allTagTree = response.data.filter(item => item.level === 1);
        this.selectDetailPage();
      })
    },
    selectDetailPage() {
      this.axios.get('/pmph/action/examOutline/selectDetailPage', {
        params: this.examOutlineDetail
      }).then((response) => {
        this.tableData = response.data.records;
        this.totalNum = response.data.total;
      })
    },
    reset() {
      this.examOutlineDetail = {
        examOutlineId: this.examOutlineId,
        examOutlineTagId: this.selectedTag.id,
        currentPage: 1, // 第几页
        pageSize: 10 // 每页显示的数据个数
      }
    },
    advanceConfirm: function () {
      this.showAdvance = false;
      this.examOutlineDetail.currentPage = 1;
      this.selectDetailPage();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    switchAppend() {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
    },
    goBack: function () {
      this.$router.push('/examOutline/list')
    },
    handleMouseOver(row) {
      this.$set(row, 'showButton', true)
    },
    handleMouseOut(row) {
      this.$set(row, 'showButton', false)
    },
    addSubTag(row) {
      if (!row.children) {
        row.children = []
      }
      this.$refs.insertTagDialog.type = 'insert'
      this.$refs.insertTagDialog.visible = true
      this.$refs.insertTagDialog.tag.level = row.level + 1
      this.$refs.insertTagDialog.tag.sort = row.children.length
      this.$refs.insertTagDialog.tag.parentId = row.id
      this.$refs.insertTagDialog.tag.parentName = row.name
      this.$refs.insertTagDialog.tag.examOutlineId = row.examOutlineId
      this.$refs.insertTagDialog.siblingTagList = row.children
    },
    editTag(row) {
      this.$refs.insertTagDialog.type = 'update'
      this.$refs.insertTagDialog.visible = true
      this.$refs.insertTagDialog.tag.id = row.id
      this.$refs.insertTagDialog.tag.sort = row.sort
      this.$refs.insertTagDialog.tag.level = row.level
      this.$refs.insertTagDialog.tag.name = row.name
      this.$refs.insertTagDialog.tag.parentId = row.parentId
      this.$refs.insertTagDialog.tag.examOutlineId = row.examOutlineId
      this.$refs.insertTagDialog.siblingTagList = this.allTagList.filter(item => item.parentId === row.parentId)
    },
    deleteTag(row) {
      this.$confirm('确认删除分类标签及子标签?', '确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post('/pmph/action/examOutline/deleteTag', row).then(() => {
          this.selectAllTagList()
        })
      })
    },
    tagMoveUp(row) {
      let preRow = this.allTagList.filter(item => (item.parentId === row.parentId) && (item.sort === row.sort - 1))[0]
      this.axios.post('/pmph/action/examOutline/tagMove', {
        preExamOutlineTag: preRow,
        curExamOutlineTag: row
      }).then(() => {
        this.selectAllTagList()
      })
    },
    tagMoveDown(row) {
      // 相当于对下一行进行上移操作;
      let nextRow = this.allTagList.filter(item => (item.parentId === row.parentId) && (item.sort === row.sort + 1))[0]
      this.tagMoveUp(nextRow)
    },
    saveTag() {
      // 重新加载页面;
      this.selectAllTagList()
    },
    addDetail() {
      this.$refs.insertDetailDialog.type = 'insert'
      this.$refs.insertDetailDialog.visible = true
      this.$refs.insertDetailDialog.examOutlineDetail.examOutlineId = this.examOutlineId
      this.$refs.insertDetailDialog.examOutlineDetail.examOutlineTagId = this.selectedTag.id
      this.$refs.insertDetailDialog.examOutlineDetail.source = 1
      this.$refs.insertDetailDialog.examOutlineDetail.parentName = UTIL.arrayToStr(this.findParentNode(this.selectedTag.id), 'name', '->')
    },
    editDetail(row) {
      this.$refs.insertDetailDialog.type = 'update'
      this.$refs.insertDetailDialog.visible = true
      this.$refs.insertDetailDialog.examOutlineDetail.id = row.id
      this.$refs.insertDetailDialog.examOutlineDetail.examOutlineId = row.examOutlineId
      this.$refs.insertDetailDialog.examOutlineDetail.examOutlineTagId = row.examOutlineTagId
      this.$refs.insertDetailDialog.examOutlineDetail.name = row.name
      this.$refs.insertDetailDialog.examOutlineDetail.requireValue = row.requireValue
      this.$refs.insertDetailDialog.examOutlineDetail.subjectValue = row.subjectValue
      this.$refs.insertDetailDialog.examOutlineDetail.source = row.source
      this.$refs.insertDetailDialog.examOutlineDetail.sort = row.sort
      this.$refs.insertDetailDialog.examOutlineDetail.parentName = UTIL.arrayToStr(this.findParentNode(row.examOutlineTagId), 'name', '->')
    },
    deleteDetail(row) {
      this.$confirm('确认删除要点?', '确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/pmph/action/examOutline/deleteDetailById', {
          params: {
            id: row.id,
            examOutlineTagId: this.selectedTag.id,
            examOutlineId: this.examOutlineId
          }
        }).then(() => {
          this.examOutlineDetail.currentPage = 1
          this.selectDetailPage()
        })
      })
    },
    batchDelete() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning("请选择待删除的要点");
        return;
      }
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/pmph/action/examOutline/deleteDetailById', {
          params: {
            id: UTIL.arrayToStr(this.multipleSelection, 'id', ','),
            examOutlineTagId: this.selectedTag.id,
            examOutlineId: this.examOutlineId
          }
        }).then(() => {
          this.examOutlineDetail.currentPage = 1
          this.selectDetailPage()
        })
      })
    },
    detailMoveUp(row) {
      let preRow = this.tableData.filter(item => item.sort === row.sort - 1)[0]
      this.axios.post('/pmph/action/examOutline/detailMove', {
        preExamOutlineDetail: preRow,
        curExamOutlineDetail: row
      }).then(() => {
        this.selectDetailPage();
      })
    },
    detailMoveDown(row) {
      // 相当于对下一行进行上移操作;
      let nextRow = this.tableData.filter(item => item.sort === row.sort + 1)[0]
      this.detailMoveUp(nextRow);
    },
    saveDetail() {
      // 重新加载页面;
      this.examOutlineDetail.currentPage = 1;
      this.selectDetailPage();
    },
    // 查找一个节点的所有父节点
    findParentNode(id) {
      let result = []
      while (true) {
        let crtNode = UTIL.findTreeNode(this.allTagTree, item => item.id === id)
        if (crtNode) {
          result.unshift(crtNode)
          id = crtNode.parentId
        } else break
      }
      return result
    },
    skipToExamKnowledge(row) {
      this.$router.push({
        path: '/guideBook/knowledgeAndExercise',
        query: {
          outlineDetailId: row.id,
          examBookId: this.bookId,
          examOutlineId: row.examOutlineId,
          pageType: 'detailList'
        }
      })
    },
    skipToExerciseGroupLibTable(row) {
      this.$router.push({
        path: '/guideBook/knowledgeAndExercise',
        query: {
          outlineDetailId: row.id,
          examBookId: this.bookId,
          examOutlineId: row.examOutlineId,
          pageType: 'exercise'
        }
      })
    },
    selectExamBookIdByExamOutlineId() {
      this.axios.get('/pmph/action/examBook/selectExamBookIdByExamOutlineId', {
        params: {
          examOutlineId: this.examOutlineId
        }
      }).then((response) => {
        if (UTIL.isNotEmpty(response.data)) {
          this.bookId = response.data.id;
        }
      })
    }
  },
  activated() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 160;
    if (this.$route.meta.isUseCache) {
      this.selectDetailPage();
      return;
    }
    this.selectedTag = {};
    this.expandRowKeyArray = [];
    this.examOutlineDetail = {
      currentPage: 1, // 第几页
      pageSize: 10 // 每页显示的数据个数
    }
    this.examOutlineId = this.$route.query.id;
    this.examOutlineDetail.examOutlineId = this.examOutlineId;
    // 初始页面,查询所有的要点
    this.selectAllTagList();
    this.selectExamBookIdByExamOutlineId();
  }
}
</script>
<style scoped>

.inline {
  display: inline-block;
}

.reorder-button {
  width: 20px;
  height: 20px;
  border-radius: 10px;
  padding: 0;
  margin: 0;
}

.el-header {
  padding: 0px;
}

.el-aside {
  padding: 0px;
}

.el-main {
  padding: 0px;
}

/deep/ .el-table__expand-icon {
  margin-right: 0px !important;
}

/deep/ ::-webkit-scrollbar {
  width: 5px;
  height: 5px;
  background-color: #F5F5F5;
}

/deep/ ::-webkit-scrollbar-thumb {
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 2px rgba(0, 0, 0, .3);
  background-color: #B3C0D1;
}

/deep/ .el-table__body {
  margin: 0px !important;
  width: 100% !important;
}

/deep/ .pl-tree-cell {
  white-space: inherit;
}

/deep/ .plTableBox .el-table .cell {
  white-space: normal;
}

/deep/ .plTableBox .el-table .umy-table-beyond {
  white-space: inherit !important;
}

</style>
